package com.rockbb.common.utilities.internet;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.rockbb.common.sso.session.SessionConstants;

public class CookiesHandler {
	private CookiesHandler() {}

	public static Cookies get(HttpServletRequest request) {
		Cookies cookies = new Cookies();
		Cookie[] cookieArray = request.getCookies();
		if (cookieArray != null) {
			String key = SessionConstants.COOKIE_KEY;
			
			for (int i = 0; i < cookieArray.length; i++ ) {
				String name = cookieArray[i].getName();
				if (name.indexOf(key) >= 0) {
					if (name.equalsIgnoreCase(key+"s")) 
						{cookies.setSession_id(cookieArray[i].getValue());}
					else if (name.equalsIgnoreCase(key+"u")) 
						{cookies.setUser_id(cookieArray[i].getValue());}
				}
			}
		}

		return cookies;
	}

	public static void setCookies(HttpServletResponse response, Cookies cookies, int expircy) {
		String key = SessionConstants.COOKIE_KEY;
		Cookie cookie = new Cookie(key+"s", cookies.getSession_id());
        cookie.setMaxAge(expircy);
        response.addCookie(cookie);

        cookie = new Cookie(key+"u", cookies.getUser_id());
        cookie.setMaxAge(expircy);
        response.addCookie(cookie);
	}

	public static void unSetCookies(HttpServletResponse response) {
		String key = SessionConstants.COOKIE_KEY;
		Cookie cookie = new Cookie(key+"s", "");
        cookie.setMaxAge(0);
        response.addCookie(cookie);

        cookie = new Cookie(key+"u", "");
        cookie.setMaxAge(0);
        response.addCookie(cookie);
	}
}
